<?php

namespace app\common\model;
require_once 'vendor/excel/PHPExcel.php';
require_once 'vendor/excel/PHPExcel/IOFactory.php';
require_once 'vendor/excel/PHPExcel/Reader/Excel5.php';

/**
 * Description of Excels
 *
 * @author Administrator
 */
class Excels
{

    /**
     * 从excel表格导入数据
     * @param type $uploadfile
     * @return type
     */
    function import($uploadfile, $fun = null)
    {
        $excel_ext = file_ext($uploadfile);
        if ($excel_ext == "xlsx")
        {
            $objReader = PHPExcel_IOFactory::createReader('Excel2007');
        }
        else
        {
            $objReader = PHPExcel_IOFactory::createReader('Excel5');
        }

        $objPHPExcel   = $objReader->load($uploadfile);
        $sheet         = $objPHPExcel->getSheet(0);
        $highestRow    = $sheet->getHighestRow();           //取得总行数 
        $highestColumn = $sheet->getHighestColumn(); //取得总列数

        for ($j = 3; $j <= $highestRow; $j++)
        {
            $arr = [];
            $str = "";
            for ($k = 'A'; $k <= $highestColumn; $k++)
            {
                $cell = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
                if ($k == $highestColumn)
                {
                    $str .= $cell;
                }
                else
                {
                    $str .= $cell . '|*|'; //读取单元格
                }
            }
            $arr = explode("|*|", $str);
            $this->$fun($arr);
        }
        return 1;
    }

    /**
     * 导出格式
     */
    function getForm($data)
    {
        return ['cols' => $data, 'data' => []];
    }

    /**
     * 导出
     * @param type $rs  $obj获取数据的模型、$fun处理数据的函数、$rs导出结构
     * $rs['cols'=>['name','length'],'data'=>[]];
     */
    function push($obj, $fun, $form)
    {
        $e           = new self();
        $rs          = $e->getForm($form);
        $name        = "订单表导出";
        // Create new PHPExcel object
        $objPHPExcel = new \PHPExcel();

        // Set properties
        $objPHPExcel->getProperties()->setCreator(cfg('sitename'));
        $objPHPExcel->getProperties()->setLastModifiedBy(cfg('sitename'));
        $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(14);
//            $objPHPExcel->getActiveSheet()->getStyle('B4:B1000')->getAlignment()->setWrapText(TRUE);
        // Add some data
        $objPHPExcel->setActiveSheetIndex(0);
        $styleArray1       = array(
            'alignment' => array(
                'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            ),
        );
        $styleArray_center = array(
            'alignment' => array(
                'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            ),
            'borders'   => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                // 'color' => array('argb' => 'FFFF0000'),  
                ),
            )
        );
        $styleArray_border = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                // 'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );

        $length     = count($rs['cols']) - 1;
        $lastLetter = chr(65 + $length);
        $objPHPExcel->getActiveSheet()->mergeCells("A1:" . $lastLetter . "1");
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', "报表导出");
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray1);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(22);

        foreach ($rs['cols'] as $k => $v)
        {
            $letter = chr(65 + $k);
            $objPHPExcel->getActiveSheet()->SetCellValue($letter . '2', $v[0]);
            $objPHPExcel->getActiveSheet()->getColumnDimension($letter)->setWidth($v[1]);
        }
        foreach ($rs['cols'] as $k => $v)
        {
            $letter = chr(65 + $k);
            $objPHPExcel->getActiveSheet()->getStyle($letter . '2')->applyFromArray($styleArray_center);
        }

        $g          = 3;
        $page       = 1; //分页数
        $obj        = "app\\common\\model\\" . $obj; //实例化数据来源类
        $obj        = new $obj();
                            
        while (!empty($rs['data'] = $obj->$fun($page++)))
        {
            foreach ($rs['data'] as $k => $v)
            {
                $i = 0;
                foreach ($v as $m => $n)
                {
                    $letter = chr(65 + $i);
                    $objPHPExcel->getActiveSheet()->SetCellValue($letter . $g, $n . ' ');
                    $i++;
                }
                $g++;
            }
        }
        
        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle('列表');


        // Save Excel 2007 file
        //$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);

        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save(str_replace('.php', '.xls', __FILE__));
        $file_name = iconv('utf-8', 'gbk', $name);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename={$file_name}.xls");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");
        exit;
    }

}
